package com.risetechnology.krystalkitchen1;

import java.io.File;

import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.risetechnology.common.Const;
import com.risetechnology.common.Shared;
import com.risetechnology.customviews.CustomFontTextView;
import com.risetechnology.data.Ingredient;
import com.risetechnology.data.Recipe;
import com.risetechnology.master.NavigationActivity;

public class ActivityEditRecipe extends NavigationActivity {
	public static final int REQUEST_CODE_CAMERA = 2001;
	public static final int REQUEST_CODE_GALLERY = 2002;
	public static final int REQUEST_CODE_CROP = 2003;

	public static String photoUrl = "temp_picture.jpg";
	public static Uri uriPicture;
	public static ImageView imageviewPhoto;

	private TextView textviewIngredients;
	private LinearLayout frameIngredients;

	private TextView textviewMethod;
	private LinearLayout frameMethod;

	private LinearLayout layoutCancel;
	private LinearLayout layoutSave;

	private TextView textviewPart1Name;
	private LinearLayout layoutPart1Ingredients;
	private CustomFontTextView textviewPart1Hint;

	private TextView textviewPart2Name;
	private LinearLayout layoutPart2Ingredients;
	private CustomFontTextView textviewPart2Hint;

	private TextView textviewPart3Name;
	private LinearLayout layoutPart3Ingredients;
	private CustomFontTextView textviewPart3Hint;

	private EditText edittextName;
	private EditText edittextServes;
	private Spinner spinnerMealType;
	private EditText edittextDescription;

	private TextView textviewPart1nameMethod;
	private LinearLayout layoutPart1Method;
	private CustomFontTextView textviewPart1MethodHint;

	private TextView textviewPart2nameMethod;
	private LinearLayout layoutPart2Method;
	private CustomFontTextView textviewPart2MethodHint;

	private TextView textviewPart3nameMethod;
	private LinearLayout layoutPart3Method;
	private CustomFontTextView textviewPart3MethodHint;

	private Recipe recipe;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_create_new_recipe);

		setContents();
	}

	private void setContents() {
		// Get recipe information
		int recipeId = getIntent().getIntExtra(Const.KEY_ID, 0);
		recipe = Shared.dbAdapter.getRecipeById(recipeId);

		frameIngredients = (LinearLayout) findViewById(R.id.frame_ingredients);
		frameMethod = (LinearLayout) findViewById(R.id.frame_method);

		imageviewPhoto = (ImageView) frameIngredients
				.findViewById(R.id.iv_image);
		imageviewPhoto.setImageDrawable(recipe.getImage());
		imageviewPhoto.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showOptionsDialog();
			}
		});

		textviewIngredients = (TextView) findViewById(R.id.tv_ingredients);
		textviewIngredients.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				textviewIngredients.setBackgroundColor(getResources().getColor(
						R.color.bg_tab_selected));
				textviewMethod.setBackgroundColor(getResources().getColor(
						R.color.bg_tab_normal));

				textviewIngredients.setTextColor(Color.WHITE);
				textviewMethod.setTextColor(getResources().getColor(
						R.color.gray));

				frameIngredients.setVisibility(View.VISIBLE);
				frameMethod.setVisibility(View.GONE);
			}
		});

		textviewMethod = (TextView) findViewById(R.id.tv_method);
		textviewMethod.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				gotoMethodPage();
			}
		});

		layoutCancel = (LinearLayout) findViewById(R.id.ll_cancel);
		layoutCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				onBackPressed();
			}
		});

		layoutSave = (LinearLayout) findViewById(R.id.ll_save);
		layoutSave.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// Toast.makeText(ActivityEditRecipe.this.getParent(),
				// "There's an error occur when saving this recipe",
				// Toast.LENGTH_LONG).show();
				saveRecipe();
			}
		});

		textviewPart1Name = (TextView) frameIngredients
				.findViewById(R.id.tv_part_1_name);
		if (recipe.getPart1Name() != null) {
			textviewPart1Name.setText(recipe.getPart1Name());
		}
		textviewPart1Name.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showPartNameDialog(1);
			}
		});

		layoutPart1Ingredients = (LinearLayout) frameIngredients
				.findViewById(R.id.layout_part_1_ingredients);

		for (Ingredient ing : Shared.dbAdapter.getIngByRecipe(recipe.getId(),
				Ingredient.INGRE1)) {

			final CustomFontTextView newIngredient = new CustomFontTextView(
					ActivityEditRecipe.this.getParent());
			newIngredient.setText(ing.toString());
			newIngredient.setTextColor(getResources().getColor(R.color.black));

			final int childCount = layoutPart1Ingredients.getChildCount();
			if (childCount == 1) {
				layoutPart1Ingredients.addView(newIngredient, 0);
				newIngredient.setPosition(0);
			} else {
				layoutPart1Ingredients.addView(newIngredient, childCount - 1);
				newIngredient.setPosition(childCount - 1);
			}

			newIngredient.setIngredient(ing);

			newIngredient.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					showEditIngredientDialog(1, newIngredient,
							newIngredient.getPosition(),
							newIngredient.getIngredient());
				}
			});
		}

		textviewPart1Hint = (CustomFontTextView) frameIngredients
				.findViewById(R.id.tv_hint_part_1_ingredients);
		textviewPart1Hint.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showAddIngredientDialog(1);
			}
		});

		textviewPart2Name = (TextView) frameIngredients
				.findViewById(R.id.tv_part_2_name);
		if (recipe.getPart2Name() != null) {
			textviewPart2Name.setText(recipe.getPart2Name());
		}
		textviewPart2Name.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showPartNameDialog(2);
			}
		});

		layoutPart2Ingredients = (LinearLayout) frameIngredients
				.findViewById(R.id.layout_part_2_ingredients);
		for (Ingredient ing : Shared.dbAdapter.getIngByRecipe(recipe.getId(),
				Ingredient.INGRE2)) {

			final CustomFontTextView newIngredient = new CustomFontTextView(
					ActivityEditRecipe.this.getParent());
			newIngredient.setText(ing.toString());
			newIngredient.setTextColor(getResources().getColor(R.color.black));

			final int childCount = layoutPart2Ingredients.getChildCount();
			if (childCount == 1) {
				layoutPart2Ingredients.addView(newIngredient, 0);
				newIngredient.setPosition(0);
			} else {
				layoutPart2Ingredients.addView(newIngredient, childCount - 1);
				newIngredient.setPosition(childCount - 1);
			}

			newIngredient.setIngredient(ing);

			newIngredient.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					showEditIngredientDialog(2, newIngredient,
							newIngredient.getPosition(),
							newIngredient.getIngredient());
				}
			});
		}

		textviewPart2Hint = (CustomFontTextView) frameIngredients
				.findViewById(R.id.tv_hint_part_2_ingredients);
		textviewPart2Hint.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showAddIngredientDialog(2);
			}
		});

		textviewPart3Name = (TextView) frameIngredients
				.findViewById(R.id.tv_part_3_name);
		if (recipe.getPart3Name() != null) {
			textviewPart3Name.setText(recipe.getPart3Name());
		}
		textviewPart3Name.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showPartNameDialog(3);
			}
		});
		layoutPart3Ingredients = (LinearLayout) frameIngredients
				.findViewById(R.id.layout_part_3_ingredients);
		for (Ingredient ing : Shared.dbAdapter.getIngByRecipe(recipe.getId(),
				Ingredient.INGRE3)) {

			final CustomFontTextView newIngredient = new CustomFontTextView(
					ActivityEditRecipe.this.getParent());
			newIngredient.setText(ing.toString());
			newIngredient.setTextColor(getResources().getColor(R.color.black));

			final int childCount = layoutPart3Ingredients.getChildCount();
			if (childCount == 1) {
				layoutPart3Ingredients.addView(newIngredient, 0);
				newIngredient.setPosition(0);
			} else {
				layoutPart3Ingredients.addView(newIngredient, childCount - 1);
				newIngredient.setPosition(childCount - 1);
			}

			newIngredient.setIngredient(ing);

			newIngredient.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					showEditIngredientDialog(3, newIngredient,
							newIngredient.getPosition(),
							newIngredient.getIngredient());
				}
			});
		}

		textviewPart3Hint = (CustomFontTextView) frameIngredients
				.findViewById(R.id.tv_hint_part_3_ingredients);
		textviewPart3Hint.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showAddIngredientDialog(3);
			}
		});

		edittextName = (EditText) frameIngredients.findViewById(R.id.et_name);
		edittextName.setText(recipe.getName());
		edittextName.setBackgroundColor(getResources().getColor(
				R.color.bg_calendar_header));

		edittextServes = (EditText) frameIngredients
				.findViewById(R.id.et_serves);
		String serves = recipe.getServes();
		// if(serves!=null && serves.contains("Serves")) serves =
		// serves.replace("Serves", "").trim();
		edittextServes.setText(serves);
		edittextServes.setBackgroundColor(getResources().getColor(
				R.color.bg_calendar_header));
		// TODO
		edittextServes.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				String text = edittextServes.getText().toString();
				if (hasFocus) {
					edittextServes.setCursorVisible(true);
					if (text.contains("Serves")) {
						edittextServes.setText(text.replace("Serves", "")
								.trim());
					}
				} else {
					edittextServes.setCursorVisible(false);
					if (text.trim().length() > 0 && !text.contains("Serves")) {
						edittextServes.setText(text.trim() + " Serves");
					}
				}
			}
		});

		edittextDescription = (EditText) frameIngredients
				.findViewById(R.id.et_description);
		edittextDescription.setText(recipe.getMainDescription());
		edittextDescription.setHintTextColor(getResources().getColor(
				R.color.hint_description));

		spinnerMealType = (Spinner) frameIngredients
				.findViewById(R.id.spn_meal_type);
		spinnerMealType.setSelection(recipe.getMealType());
		String[] mealTypes = getResources().getStringArray(R.array.meal_types);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.spinner_item, mealTypes);
		spinnerMealType.setAdapter(adapter);
		spinnerMealType.setSelection(recipe.getMealType());

		// TODO
		layoutPart1Method = (LinearLayout) frameMethod
				.findViewById(R.id.layout_part_1_method);

		for (String instruction : recipe.getPart1Method().split("#")) {
			if (instruction.trim().length() == 0)
				continue;

			final CustomFontTextView newInstruction = new CustomFontTextView(
					ActivityEditRecipe.this.getParent());
			newInstruction.setValue(instruction);
			newInstruction.setText(instruction);
			newInstruction.setTextColor(getResources().getColor(R.color.black));

			final int childCount = layoutPart1Method.getChildCount();

			if (childCount == 1) {
				layoutPart1Method.addView(newInstruction, 0);
				newInstruction.setPosition(0);
			} else {
				layoutPart1Method.addView(newInstruction, childCount - 1);
				newInstruction.setPosition(childCount - 1);
			}

			newInstruction.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					showEditInstructionsDialog(1, newInstruction,
							newInstruction.getPosition(), newInstruction
									.getText().toString());
				}
			});
		}

		textviewPart1nameMethod = (TextView) frameMethod
				.findViewById(R.id.tv_part_1_name);
		if (recipe.getPart1MethodName() != null) {
			textviewPart1nameMethod.setText(recipe.getPart1MethodName());
		}
		textviewPart1nameMethod.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showMethodPartNameDialog(1);
			}
		});
		textviewPart1MethodHint = (CustomFontTextView) frameMethod
				.findViewById(R.id.tv_part_1_hint_method);
		textviewPart1MethodHint.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showAddInstructionDialog(1);
			}
		});

		layoutPart2Method = (LinearLayout) frameMethod
				.findViewById(R.id.layout_part_2_method);
		if (recipe.getPart2Method() != null) {
			for (String instruction : recipe.getPart2Method().split("#")) {
				if (instruction.trim().length() == 0)
					continue;

				final CustomFontTextView newInstruction = new CustomFontTextView(
						ActivityEditRecipe.this.getParent());
				newInstruction.setValue(instruction);
				newInstruction.setText(instruction);
				newInstruction.setTextColor(getResources().getColor(
						R.color.black));

				final int childCount = layoutPart2Method.getChildCount();

				if (childCount == 1) {
					layoutPart2Method.addView(newInstruction, 0);
					newInstruction.setPosition(0);
				} else {
					layoutPart2Method.addView(newInstruction, childCount - 1);
					newInstruction.setPosition(childCount - 1);
				}

				newInstruction.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						showEditInstructionsDialog(2, newInstruction,
								newInstruction.getPosition(), newInstruction
										.getText().toString());
					}
				});
			}
		}

		textviewPart2nameMethod = (TextView) frameMethod
				.findViewById(R.id.tv_part_2_name);
		if (recipe.getPart2MethodName() != null) {
			textviewPart2nameMethod.setText(recipe.getPart2MethodName());
		}
		textviewPart2nameMethod.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showMethodPartNameDialog(2);
			}
		});
		textviewPart2MethodHint = (CustomFontTextView) frameMethod
				.findViewById(R.id.tv_part_2_hint_method);
		textviewPart2MethodHint.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showAddInstructionDialog(2);
			}
		});

		layoutPart3Method = (LinearLayout) frameMethod
				.findViewById(R.id.layout_part_3_method);
		if (recipe.getPart3Method() != null) {
			for (String instruction : recipe.getPart3Method().split("#")) {
				if (instruction.trim().length() == 0)
					continue;

				final CustomFontTextView newInstruction = new CustomFontTextView(
						ActivityEditRecipe.this.getParent());
				newInstruction.setValue(instruction);
				newInstruction.setText(instruction);
				newInstruction.setTextColor(getResources().getColor(
						R.color.black));

				final int childCount = layoutPart3Method.getChildCount();

				if (childCount == 1) {
					layoutPart3Method.addView(newInstruction, 0);
					newInstruction.setPosition(0);
				} else {
					layoutPart3Method.addView(newInstruction, childCount - 1);
					newInstruction.setPosition(childCount - 1);
				}

				newInstruction.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						showEditInstructionsDialog(3, newInstruction,
								newInstruction.getPosition(), newInstruction
										.getText().toString());
					}
				});
			}
		}

		textviewPart3nameMethod = (TextView) frameMethod
				.findViewById(R.id.tv_part_3_name);
		if (recipe.getPart3MethodName() != null) {
			textviewPart3nameMethod.setText(recipe.getPart3MethodName());
		}
		textviewPart3nameMethod.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showMethodPartNameDialog(3);
			}
		});
		textviewPart3MethodHint = (CustomFontTextView) frameMethod
				.findViewById(R.id.tv_part_3_hint_method);
		textviewPart3MethodHint.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showAddInstructionDialog(3);
			}
		});
	}

	private void gotoMethodPage() {
		textviewMethod.setBackgroundColor(getResources().getColor(
				R.color.bg_tab_selected));
		textviewIngredients.setBackgroundColor(getResources().getColor(
				R.color.bg_tab_normal));

		textviewMethod.setTextColor(Color.WHITE);
		textviewIngredients.setTextColor(getResources().getColor(R.color.gray));

		frameIngredients.setVisibility(View.GONE);
		frameMethod.setVisibility(View.VISIBLE);
	}

	private void saveRecipe() {
		String name = edittextName.getText().toString();
		if (name == null || name.length() == 0) {
			Toast.makeText(ActivityEditRecipe.this.getParent(),
					"Please input name", Toast.LENGTH_SHORT).show();
			return;
		}

		String serves = edittextServes.getText().toString();
		if (serves == null || serves.length() == 0) {
			Toast.makeText(ActivityEditRecipe.this.getParent(),
					"Please input serves", Toast.LENGTH_SHORT).show();
			return;
		}

		Drawable drawable = imageviewPhoto.getDrawable();
		int mealTypeId = spinnerMealType.getSelectedItemPosition();
		String description = edittextDescription.getText().toString();

		String part1Name = textviewPart1Name.getText().toString();
		String part1Ingredients = "";
		// for (int i = 0; i < layoutPart1Ingredients.getChildCount() - 1; i++)
		// {
		// part1Ingredients +=
		// ((TextView)layoutPart1Ingredients.getChildAt(i)).getText().toString()
		// + "#";
		// }

		String part2Name = textviewPart2Name.getText().toString();
		String part2Ingredients = "";
		// for (int i = 0; i < layoutPart2Ingredients.getChildCount() - 1; i++)
		// {
		// part2Ingredients +=
		// ((TextView)layoutPart2Ingredients.getChildAt(i)).getText().toString()
		// + "#";
		// }

		String part3Name = textviewPart3Name.getText().toString();
		String part3Ingredients = "";
		// for (int i = 0; i < layoutPart3Ingredients.getChildCount() - 1; i++)
		// {
		// part3Ingredients +=
		// ((TextView)layoutPart3Ingredients.getChildAt(i)).getText().toString()
		// + "#";
		// }

		String part1MethodName = textviewPart1nameMethod.getText().toString()
				.trim();
		// if(part1MethodName.length()==0 ||
		// part1MethodName.equals("Part 1 Name...")&&
		// layoutPart1Method.getChildCount()>1){
		// gotoMethodPage();
		// Toast.makeText(this.getParent(), "Please input Method Part 1 Name",
		// Toast.LENGTH_SHORT).show();
		// return;
		// }

		String part1Method = "";
		for (int i = 0; i < layoutPart1Method.getChildCount() - 1; i++) {
			part1Method += ((CustomFontTextView) layoutPart1Method
					.getChildAt(i)).getValue() + "#";
		}

		String part2MethodName = textviewPart2nameMethod.getText().toString()
				.trim();
		// if(part2MethodName.length()==0 ||
		// part2MethodName.equals("Part 2 Name...")&&
		// layoutPart2Method.getChildCount()>1){
		// gotoMethodPage();
		// Toast.makeText(this.getParent(), "Please input Method Part 2 Name",
		// Toast.LENGTH_SHORT).show();
		// return;
		// }

		String part2Method = "";
		for (int i = 0; i < layoutPart2Method.getChildCount() - 1; i++) {
			part2Method += ((CustomFontTextView) layoutPart2Method
					.getChildAt(i)).getValue() + "#";
		}

		String part3MethodName = textviewPart3nameMethod.getText().toString()
				.trim();
		// if(part3MethodName.length()==0 ||
		// part3MethodName.equals("Part 3 Name...")&&
		// layoutPart3Method.getChildCount()>1){
		// gotoMethodPage();
		// Toast.makeText(this.getParent(), "Please input Method Part 3 Name",
		// Toast.LENGTH_SHORT).show();
		// return;
		// }

		String part3Method = "";
		for (int i = 0; i < layoutPart3Method.getChildCount() - 1; i++) {
			part3Method += ((CustomFontTextView) layoutPart3Method
					.getChildAt(i)).getValue() + "#";
		}

		Recipe recipe = new Recipe(this.recipe.getId(), name, serves,
				mealTypeId, description, 0, false, drawable, part1Name,
				part1Ingredients, part2Name, part2Ingredients, part3Name,
				part3Ingredients, part1MethodName, part1Method,
				part2MethodName, part2Method, part3MethodName, part3Method, 0, "");

		Shared.dbAdapter.updateRecipe(recipe);
		int recipeId = recipe.getId();
		for (int i = 0; i < layoutPart1Ingredients.getChildCount() - 1; i++) {
			View v = layoutPart1Ingredients.getChildAt(i);
			if (v instanceof CustomFontTextView) {
				CustomFontTextView ctv = (CustomFontTextView) v;
				if (null != ctv.getIngredient()) {
					Ingredient ing = ctv.getIngredient();
					ing.setRecipeId(recipeId);
					Shared.dbAdapter.addIngredient(ing);
				}
			}
		}

		for (int i = 0; i < layoutPart2Ingredients.getChildCount() - 1; i++) {
			View v = layoutPart2Ingredients.getChildAt(i);
			if (v instanceof CustomFontTextView) {
				CustomFontTextView ctv = (CustomFontTextView) v;
				if (null != ctv.getIngredient()) {
					Ingredient ing = ctv.getIngredient();
					ing.setRecipeId(recipeId);
					Shared.dbAdapter.addIngredient(ing);
				}
			}
		}

		for (int i = 0; i < layoutPart3Ingredients.getChildCount() - 1; i++) {
			View v = layoutPart3Ingredients.getChildAt(i);
			if (v instanceof CustomFontTextView) {
				CustomFontTextView ctv = (CustomFontTextView) v;
				if (null != ctv.getIngredient()) {
					Ingredient ing = ctv.getIngredient();
					ing.setRecipeId(recipeId);
					Shared.dbAdapter.addIngredient(ing);
				}
			}
		}

		ActivityRecipes.getRecipesList();
		ActivityRecipes.getRecipesListMasalas();

		hideKeyboard();

		onBackPressed();
	}

	private void hideKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(edittextName.getWindowToken(), 0);
	}

	@SuppressWarnings("deprecation")
	private void showPartNameDialog(final int partId) {
		final Dialog dialog = new Dialog(ActivityEditRecipe.this.getParent());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_input_part_name);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		dialog.show();

		final EditText edittextName = (EditText) dialog
				.findViewById(R.id.et_part_name);

		Button buttonOK = (Button) dialog.findViewById(R.id.btn_ok);
		buttonOK.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String name = edittextName.getText().toString();
				if (name == null || name.length() == 0) {
					String partName = "Part " + partId + " Name...";
					if (partId == 1) {
						textviewPart1Name.setText(partName);
					} else if (partId == 2) {
						textviewPart2Name.setText(partName);
					} else if (partId == 3) {
						textviewPart3Name.setText(partName);
					}
				} else {
					if (partId == 1) {
						textviewPart1Name.setText(name);
					} else if (partId == 2) {
						textviewPart2Name.setText(name);
					} else if (partId == 3) {
						textviewPart3Name.setText(name);
					}
				}
				dialog.dismiss();
			}
		});
	}

	@SuppressWarnings("deprecation")
	private void showMethodPartNameDialog(final int partId) {
		final Dialog dialog = new Dialog(ActivityEditRecipe.this.getParent());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_input_part_name);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		dialog.show();

		final EditText edittextName = (EditText) dialog
				.findViewById(R.id.et_part_name);

		Button buttonOK = (Button) dialog.findViewById(R.id.btn_ok);
		buttonOK.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String name = edittextName.getText().toString();
				if (name == null || name.length() == 0) {
					String partName = "Part " + partId + " Name...";
					if (partId == 1) {
						textviewPart1nameMethod.setText(partName);
					} else if (partId == 2) {
						textviewPart2nameMethod.setText(partName);
					} else if (partId == 3) {
						textviewPart3nameMethod.setText(partName);
					}
				} else {
					if (partId == 1) {
						textviewPart1nameMethod.setText(name);
					} else if (partId == 2) {
						textviewPart2nameMethod.setText(name);
					} else if (partId == 3) {
						textviewPart3nameMethod.setText(name);
					}
				}
				dialog.dismiss();
			}
		});
	}

	@SuppressWarnings("deprecation")
	private void showAddIngredientDialog(final int partId) {
		final Dialog dialog = new Dialog(ActivityEditRecipe.this.getParent());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_add_ingredients);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		dialog.show();

		final EditText edittextQuantity = (EditText) dialog
				.findViewById(R.id.et_quantity);
		final EditText edittextUnit = (EditText) dialog
				.findViewById(R.id.et_unit);
		final EditText edittextName = (EditText) dialog
				.findViewById(R.id.et_name);
		final EditText edittextdescription = (EditText) dialog
				.findViewById(R.id.et_description);

		Button buttonOK = (Button) dialog.findViewById(R.id.btn_ok);
		buttonOK.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				final String quantity = edittextQuantity.getText().toString();
				final String unit = edittextUnit.getText().toString();
				final String name = edittextName.getText().toString();
				final String description = edittextdescription.getText()
						.toString();

				boolean isValid = validateAddIngredientForm(quantity, unit,
						name, description);
				if (isValid) {
					dialog.dismiss();

					String ingredients = quantity + " " + unit + " " + name
							+ " " + description;

					Ingredient ingredient = new Ingredient(quantity, unit,
							name, description, -1, partId, false);

					if (partId == 1) {
						final CustomFontTextView newIngredient = new CustomFontTextView(
								ActivityEditRecipe.this.getParent());
						newIngredient.setText(ingredients);
						newIngredient.setTextColor(getResources().getColor(
								R.color.black));

						final int childCount = layoutPart1Ingredients
								.getChildCount();
						if (childCount == 1) {
							layoutPart1Ingredients.addView(newIngredient, 0);
							newIngredient.setPosition(0);
						} else {
							layoutPart1Ingredients.addView(newIngredient,
									childCount - 1);
							newIngredient.setPosition(childCount - 1);
						}

						newIngredient.setIngredient(ingredient);

						newIngredient.setOnClickListener(new OnClickListener() {
							public void onClick(View v) {
								showEditIngredientDialog(1, newIngredient,
										newIngredient.getPosition(),
										newIngredient.getIngredient());
							}
						});

					} else if (partId == 2) {
						final CustomFontTextView newIngredient = new CustomFontTextView(
								ActivityEditRecipe.this.getParent());
						newIngredient.setText(ingredients);
						newIngredient.setTextColor(getResources().getColor(
								R.color.black));

						final int childCount = layoutPart2Ingredients
								.getChildCount();
						if (childCount == 1) {
							layoutPart2Ingredients.addView(newIngredient, 0);
							newIngredient.setPosition(0);
						} else {
							layoutPart2Ingredients.addView(newIngredient,
									childCount - 1);
							newIngredient.setPosition(childCount - 1);
						}

						newIngredient.setIngredient(ingredient);

						newIngredient.setOnClickListener(new OnClickListener() {
							public void onClick(View v) {
								showEditIngredientDialog(2, newIngredient,
										newIngredient.getPosition(),
										newIngredient.getIngredient());
							}
						});
					} else if (partId == 3) {
						final CustomFontTextView newIngredient = new CustomFontTextView(
								ActivityEditRecipe.this.getParent());
						newIngredient.setText(ingredients);
						newIngredient.setTextColor(getResources().getColor(
								R.color.black));

						final int childCount = layoutPart3Ingredients
								.getChildCount();
						if (childCount == 1) {
							layoutPart3Ingredients.addView(newIngredient, 0);
							newIngredient.setPosition(0);
						} else {
							layoutPart3Ingredients.addView(newIngredient,
									childCount - 1);
							newIngredient.setPosition(childCount - 1);
						}

						newIngredient.setIngredient(ingredient);

						newIngredient.setOnClickListener(new OnClickListener() {
							public void onClick(View v) {
								showEditIngredientDialog(3, newIngredient,
										newIngredient.getPosition(),
										newIngredient.getIngredient());
							}
						});

					}
				}
			}
		});
	}

	@SuppressWarnings("deprecation")
	private void showAddInstructionDialog(final int partId) {
		final Dialog dialog = new Dialog(ActivityEditRecipe.this.getParent());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_add_instruction);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		dialog.show();

		final EditText editTextInstruction = (EditText) dialog
				.findViewById(R.id.et_instructions);

		Button buttonOK = (Button) dialog.findViewById(R.id.btn_ok);
		buttonOK.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (editTextInstruction == null
						|| editTextInstruction.length() == 0) {
					Toast.makeText(ActivityEditRecipe.this.getParent(),
							"Please input instruction", Toast.LENGTH_SHORT)
							.show();
					return;
				} else {
					final String instruction = editTextInstruction.getText()
							.toString();
					if (partId == 1) {
						dialog.dismiss();

						final CustomFontTextView newInstruction = new CustomFontTextView(
								ActivityEditRecipe.this.getParent());
						newInstruction.setValue(instruction);
						newInstruction.setText(instruction);
						newInstruction.setTextColor(getResources().getColor(
								R.color.black));

						final int childCount = layoutPart1Method
								.getChildCount();

						if (childCount == 1) {
							layoutPart1Method.addView(newInstruction, 0);
							newInstruction.setPosition(0);
						} else {
							layoutPart1Method.addView(newInstruction,
									childCount - 1);
							newInstruction.setPosition(childCount - 1);
						}

						newInstruction
								.setOnClickListener(new OnClickListener() {
									public void onClick(View v) {
										showEditInstructionsDialog(1,
												newInstruction, newInstruction
														.getPosition(),
												newInstruction.getText()
														.toString());
									}
								});
					} else if (partId == 2) {
						dialog.dismiss();

						final CustomFontTextView newInstruction = new CustomFontTextView(
								ActivityEditRecipe.this.getParent());
						newInstruction.setValue(instruction);
						newInstruction.setText(instruction);
						newInstruction.setTextColor(getResources().getColor(
								R.color.black));

						final int childCount = layoutPart2Method
								.getChildCount();

						if (childCount == 1) {
							layoutPart2Method.addView(newInstruction, 0);
							newInstruction.setPosition(0);
						} else {
							layoutPart2Method.addView(newInstruction,
									childCount - 1);
							newInstruction.setPosition(childCount - 1);
						}

						newInstruction
								.setOnClickListener(new OnClickListener() {
									public void onClick(View v) {
										showEditInstructionsDialog(2,
												newInstruction, newInstruction
														.getPosition(),
												newInstruction.getText()
														.toString());
									}
								});
					} else if (partId == 3) {
						dialog.dismiss();

						final CustomFontTextView newInstruction = new CustomFontTextView(
								ActivityEditRecipe.this.getParent());
						newInstruction.setValue(instruction);
						newInstruction.setText(instruction);
						newInstruction.setTextColor(getResources().getColor(
								R.color.black));

						final int childCount = layoutPart3Method
								.getChildCount();

						if (childCount == 1) {
							layoutPart3Method.addView(newInstruction, 0);
							newInstruction.setPosition(0);
						} else {
							layoutPart3Method.addView(newInstruction,
									childCount - 1);
							newInstruction.setPosition(childCount - 1);
						}

						newInstruction
								.setOnClickListener(new OnClickListener() {
									public void onClick(View v) {
										showEditInstructionsDialog(3,
												newInstruction, newInstruction
														.getPosition(),
												newInstruction.getText()
														.toString());
									}
								});
					}
				}
			}
		});
	}

	@SuppressWarnings("deprecation")
	private void showEditIngredientDialog(final int partId,
			final CustomFontTextView textview, int position,
			Ingredient ingredient) {
		final Dialog dialog = new Dialog(ActivityEditRecipe.this.getParent());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_edit_ingredient);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		dialog.show();

		final EditText edittextQuantity = (EditText) dialog
				.findViewById(R.id.et_quantity);
		edittextQuantity.setText("" + ingredient.getQuantity());
		final EditText edittextUnit = (EditText) dialog
				.findViewById(R.id.et_unit);
		edittextUnit.setText(ingredient.getUnit());
		final EditText edittextName = (EditText) dialog
				.findViewById(R.id.et_name);
		edittextName.setText(ingredient.getName());
		final EditText edittextdescription = (EditText) dialog
				.findViewById(R.id.et_description);
		edittextdescription.setText(ingredient.getDescription());
		final int type = ingredient.getType();
		final int id = ingredient.getID();

		Button buttonDelete = (Button) dialog.findViewById(R.id.btn_delete);
		buttonDelete.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				if (partId == 1) {
					// part1IngredientsList.remove(position);
					layoutPart1Ingredients.removeViewAt(textview.getPosition());
				} else if (partId == 2) {
					// part2IngredientsList.remove(position);
					layoutPart2Ingredients.removeViewAt(textview.getPosition());
				} else if (partId == 3) {
					// part3IngredientsList.remove(position);
					layoutPart3Ingredients.removeViewAt(textview.getPosition());
				}
				if (id > 0) {
					Shared.dbAdapter.deleteIngredient(id);
				}
			}
		});
		Button buttonSaveEdits = (Button) dialog
				.findViewById(R.id.btn_save_edits);
		buttonSaveEdits.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String newQuantity = edittextQuantity.getText().toString();
				String newUnit = edittextUnit.getText().toString();
				String newName = edittextName.getText().toString();
				String newDescription = edittextdescription.getText()
						.toString();
				if (validateAddIngredientForm(newQuantity, newUnit, newName,
						newDescription)) {
					dialog.dismiss();

					String newIngredient = newQuantity + " " + newUnit + " "
							+ newName + " " + newDescription;

					Ingredient newIngredientItem = new Ingredient(newQuantity,
							newUnit, newName, newDescription, -1, type, false);
					textview.setIngredient(newIngredientItem);

					textview.setText(newIngredient);
				}
			}
		});
	}

	@SuppressWarnings("deprecation")
	private void showEditInstructionsDialog(final int partId,
			final CustomFontTextView textview, final int position,
			final String instructions) {

		final Dialog dialog = new Dialog(ActivityEditRecipe.this.getParent());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_edit_instruction);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		dialog.show();

		final EditText editTextInstruction = (EditText) dialog
				.findViewById(R.id.et_instructions);
		editTextInstruction.setText(instructions);

		Button buttonDelete = (Button) dialog.findViewById(R.id.btn_delete);
		buttonDelete.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				if (partId == 1) {
					layoutPart1Method.removeViewAt(position);
				} else if (partId == 2) {
					layoutPart2Method.removeViewAt(position);
				} else if (partId == 3) {
					layoutPart3Method.removeViewAt(position);
				}
			}
		});
		Button buttonSaveEdits = (Button) dialog
				.findViewById(R.id.btn_save_edits);
		buttonSaveEdits.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String newInstruction = editTextInstruction.getText()
						.toString();
				if (newInstruction == null || newInstruction.length() == 0) {
					Toast.makeText(ActivityEditRecipe.this.getParent(),
							"Please input instruction", Toast.LENGTH_SHORT)
							.show();
					return;
				} else {
					dialog.dismiss();

					textview.setValue(newInstruction);
					textview.setText(newInstruction);
				}
			}
		});
	}

	private boolean validateAddIngredientForm(String quantity, String unit,
			String name, String description) {
		float q = 0f;
		try {
			q = Float.parseFloat(quantity);
		} catch (Exception e) {
			// TODO: handle exception
		}
		if (quantity == null || quantity.length() == 0 || q == 0f) {
			Toast.makeText(ActivityEditRecipe.this.getParent(),
					"Please input quantity", Toast.LENGTH_SHORT).show();
			return false;
		} else if (unit == null || unit.length() == 0) {
			Toast.makeText(ActivityEditRecipe.this.getParent(),
					"Please input unit", Toast.LENGTH_SHORT).show();
			return false;
		} else if (name == null || name.length() == 0) {
			Toast.makeText(ActivityEditRecipe.this.getParent(),
					"Please input name", Toast.LENGTH_SHORT).show();
			return false;
		}
		// else if (description == null || description.length() == 0) {
		// Toast.makeText(ActivityEditRecipe.this.getParent(),
		// "Please input description", Toast.LENGTH_SHORT).show();
		// return false;
		// }

		return true;
	}

	@SuppressWarnings("deprecation")
	private void showOptionsDialog() {

		final Dialog dialog = new Dialog(ActivityEditRecipe.this.getParent());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_photo_picker_options);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		LinearLayout cameraLayout = (LinearLayout) dialog
				.findViewById(R.id.layout_camera);
		cameraLayout.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();

				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				uriPicture = Uri.fromFile(new File(Environment
						.getExternalStorageDirectory(), photoUrl));
				intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
						uriPicture);
				try {
					intent.putExtra("return-data", true);
					ActivityEditRecipe.this.getParent().startActivityForResult(
							intent, ActivityEditRecipe.REQUEST_CODE_CAMERA);
				} catch (ActivityNotFoundException e) {
					e.printStackTrace();
				}
			}
		});

		LinearLayout galleryLayout = (LinearLayout) dialog
				.findViewById(R.id.layout_gallery);
		galleryLayout.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();

				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				ActivityEditRecipe.this.getParent().startActivityForResult(
						Intent.createChooser(intent, "Complete action using"),
						ActivityEditRecipe.REQUEST_CODE_GALLERY);
			}
		});

		dialog.show();
	}
}
